// 注意：此文件需要在安装gRPC后编译
// 编译前请确保已安装gRPC和protobuf库

#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <chrono>
#include <unistd.h>

// gRPC头文件 - 编译时会自动找到正确路径
#include <grpcpp/grpcpp.h>
#include "chat.grpc.pb.h"

using grpc::Channel;
using grpc::ClientContext;
using grpc::ClientReaderWriter;
using grpc::Status;
using chat::ChatMessage;
using chat::ChatService;

class ChatClient {
public:
    ChatClient(std::shared_ptr<Channel> channel)
        : stub_(ChatService::NewStub(channel)) {}
    
    void StartChat() {
        ClientContext context;
        
        // 添加客户端元数据，服务器可以通过ServerContext解析这些信息
        context.AddMetadata("client-name", "ChatClient");
        context.AddMetadata("client-version", "1.0.0");
        context.AddMetadata("user-agent", "gRPC-C++/1.74.0");
        context.AddMetadata("client-os", "macOS");
        context.AddMetadata("session-id", std::to_string(getpid()));
        
        // 设置请求超时时间 (可选)
        auto deadline = std::chrono::system_clock::now() + std::chrono::seconds(300); // 5分钟超时
        context.set_deadline(deadline);
        
        std::shared_ptr<ClientReaderWriter<ChatMessage, ChatMessage>> stream(
            stub_->Chat(&context));
        
        // 启动读取线程来接收服务器消息
        std::thread reader_thread([stream]() {
            ChatMessage server_message;
            while (stream->Read(&server_message)) {
                std::cout << "\n收到服务器消息 [" << server_message.user() << "]: " 
                        << server_message.message() << std::endl;
                std::cout << "请输入消息 (输入 'quit' 退出): ";
                std::cout.flush();
            }
        });
        
        std::cout << "连接到聊天服务器成功!" << std::endl;
        std::cout << "请输入消息 (输入 'quit' 退出): ";
        
        std::string input;
        int message_count = 0;
        while (std::getline(std::cin, input)) {
            if (input == "quit") {
                break;
            }
            
            if (!input.empty()) {
                ChatMessage message;
                message.set_user("Client_" + std::to_string(getpid()));
                message.set_message(input);
                message.set_timestamp(std::chrono::duration_cast<std::chrono::seconds>(
                    std::chrono::system_clock::now().time_since_epoch()).count());
                
                if (!stream->Write(message)) {
                    std::cout << "发送消息失败，连接可能已断开" << std::endl;
                    break;
                }
                message_count++;
            }
            
            std::cout << "请输入消息 (输入 'quit' 退出): ";
        }
        
        // 关闭写入流
        stream->WritesDone();
        
        // 等待读取线程结束
        reader_thread.join();
        
        // 获取最终状态
        Status status = stream->Finish();
        if (status.ok()) {
            std::cout << "聊天会话正常结束" << std::endl;
        } else {
            std::cout << "聊天会话异常结束: " << status.error_message() << std::endl;
        }
    }

private:
    std::unique_ptr<ChatService::Stub> stub_;
};

int main(int argc, char** argv) {
    std::string server_address("localhost:8080");
    
    // 创建gRPC通道
    auto channel = grpc::CreateChannel(server_address, grpc::InsecureChannelCredentials());
    
    ChatClient client(channel);
    client.StartChat();
    
    return 0;
}